<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">

      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单发起日期" prop="orderDate">
        <el-date-picker clearable
          v-model="queryParams.orderDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择订单发起日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="业务所属公司" prop="businessCompany">
        <el-select v-model="queryParams.businessCompany" placeholder="业务所属公司">
          <el-option
            v-for="item in contractTemplateOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目地区域" prop="projectArea">
        <el-select v-model="queryParams.projectArea" placeholder="项目地区域">
          <el-option
            v-for="item in regionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:order:delete']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['module:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button   v-hasPermi="['module:outboundOrder:warning']" type="danger" plain size="mini" @click="handleWaring">查看预警订单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">


      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同模板" align="center" prop="contractTemplate" />
      <el-table-column label="发起人" align="center" prop="sponsorName" />
      <el-table-column label="业务员" align="center" prop="salesmanName" />
      <el-table-column label="协同人" align="center" prop="collaboratorName" />
      <el-table-column label="信息提供人" align="center" prop="informationProviderName" width="100"/>
      <el-table-column label="发起人所属部门" align="center" prop="sponsorDeptName" width="150" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="订单发起日期" align="center" prop="orderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="业务所属公司" align="center" prop="businessCompany" width="100" />
      <el-table-column label="订单类型" align="center" prop="orderType" />
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="客户类别" align="center" prop="customerCategory" />
      <el-table-column label="客户信息来源" align="center" prop="customerSource" width="100" />
      <el-table-column label="客户所属省份" align="center" prop="customerRegion" width="100"/>
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="项目地区域" align="center" prop="projectArea" width="100"/>
      <el-table-column label="项目信息来源" align="center" prop="projectSource" width="100"/>
      <el-table-column label="租赁形式" align="center" prop="lease" />
      <el-table-column label="收货地址" align="center" prop="address" />
      <el-table-column label="收货人姓名" align="center" prop="consigneeName" width="100"/>
      <el-table-column label="收货人电话" align="center" prop="consigneeTel" width="100"/>
      <el-table-column label="发货仓库" align="center" prop="deliveryWarehouseName" />
      <el-table-column label="辅料说明" align="center" prop="accessoriesInstruction" />
      <el-table-column label="日租金合计" align="center" prop="totalDailyRent" width="100" />
<!--      <el-table-column label="租金合计" align="center" prop="totalRant" >-->

<!--      </el-table-column>>-->
      <el-table-column width="200px" label="应收押金" align="center" prop="depositReceivable" >
        <template slot-scope="scope">
          <span style="margin-right:10px">{{  scope.row.depositReceivable }}</span>
          <el-button type="text" @click="addmoney(scope.row.id)">追加押金</el-button>
        </template>
      </el-table-column>>
      <el-table-column label="押金收取方式" align="center" prop="depositCollectionMethod" width="100"/>
      <el-table-column label="应收款" align="center" prop="receivables" />
      <el-table-column label="业务费情况" align="center" prop="businessExpenses" width="100"/>
      <el-table-column label="期望到货日期" align="center" prop="expectedArrivalDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedArrivalDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="运输方式" align="center" prop="shippingType" />-->
<!--      <el-table-column label="司机姓名" align="center" prop="driverName" />-->
<!--      <el-table-column label="司机联系方式" align="center" prop="driverTel" width="100"/>-->
<!--      <el-table-column label="车辆信息" align="center" prop="vehicleInformation" />-->
      <el-table-column label="发货状态" align="center" prop="shipmentStatus" >
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.shipmentStatus == '1'" >缺货</el-button>
          <el-button type="text" v-if="scope.row.shipmentStatus == '2'" >代发货</el-button>
          <el-button type="text" v-if="scope.row.shipmentStatus == '3'" >已发货</el-button>
        </template>
      </el-table-column>
      <el-table-column label="情况说明" align="center" prop="description" />
      <el-table-column label="出库状态" align="center" prop="deliveryStatus" >
        <template slot-scope="scope">
          <el-button type="text" v-if="scope.row.deliveryStatus == '1'" >待出库</el-button>
          <el-button type="text" v-if="scope.row.deliveryStatus == '2'" >已出库</el-button>
        </template>
      </el-table-column>
      <el-table-column width="200px" label="订单状态" align="center" prop="orderStatus" >
        <template   slot-scope="scope">
          <el-button type="text" v-if="scope.row.orderStatus == '0'" >市场部待审批中</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '8'" >财务部待审批</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '1'" >代发货</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '7'" >发货中</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '2'" >已出库</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '9'" >申请中</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '3'" >已申请</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '10'" >入库中</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '4'" >已入库</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '5'" >已对账</el-button>
          <el-button type="text" v-if="scope.row.orderStatus == '6'" >已完结</el-button>
        </template>
      </el-table-column>

<!--      <el-table-column label="已收金额" align="center" prop="receivedAmount" />-->
<!--      <el-table-column label="未收金额" align="center" prop="unreceivedAmount" />-->
<!--      <el-table-column label="坏账金额" align="center" prop="badDebtAmount" />-->
<!--      <el-table-column label="开票金额" align="center" prop="invoicedAmount" />-->
<!--      <el-table-column label="未开票金额" align="center" prop="uninvoicedAmount" width="100"/>-->
      <el-table-column fixed="right" label="市场部审批" align="center"  width="100px">
        <template slot-scope="scope">
          <el-button @click="updateFn1(scope.row)"   v-hasPermi="['module:order:updateStatus1']" v-if="scope.row.orderStatus=='0'" type="success" size="mini">一键通过</el-button>
          <el-button @click="updateFn2(scope.row)" v-if="scope.row.purview==1 && scope.row.orderStatus=='11'"  v-hasPermi="['module:order:updateStatus2']" type="success" size="mini">超权限审批</el-button>
          <el-button @click="openApproval(scope.row)" type="text">审批记录</el-button>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="财务审批" align="center"  width="100px">
        <template slot-scope="scope">
          <el-button @click="updateFn(scope.row)"   v-hasPermi="['module:order:updateStatus']" v-if="scope.row.orderStatus=='8'" type="success" size="mini">一键通过</el-button>
          <el-button @click="openApproval(scope.row)" type="text">审批记录</el-button>
        </template>
      </el-table-column>
      <el-table-column width="200" label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:order:update']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleProduct(scope.row)"
            v-hasPermi="['module:order:delete']"
          >关联产品</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handelerOrderList(scope.row)"
          >维修订单</el-button>
          <el-button
            size="mini"
            type="text"
            @click="openProjectList(scope.row)"
          >项目支出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" inline  :model="form" :rules="rules" label-width="140px">
        <el-form-item label="合同模板" prop="contractTemplate">
          <el-select v-model="form.contractTemplate" placeholder="合同模板">
            <el-option
              v-for="item in contractTemplateOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="发起人" prop="sponsor">
          <el-input v-model="form.sponsor" placeholder="请输入发起人" />
        </el-form-item>-->
        <el-form-item  label="发起人名称" prop="sponsorName">
          <el-input   v-model="form.sponsorName" readonly placeholder="请输入发起人名称" />
        </el-form-item>
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="form.orderNo" readonly placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item style="margin-left: 15px" label="发起人所属部门名称" prop="sponsorDeptName">
          <el-input   v-model="form.sponsorDeptName" readonly placeholder="请输入发起人所属部门名称" />
        </el-form-item>
<!--        <el-form-item label="业务员" prop="salesman">
          <el-input v-model="form.salesman" placeholder="请输入业务员" />
        </el-form-item>-->
        <el-form-item label="业务员名称" prop="salesmanName">
          <el-input style="width: 250px" v-model="form.salesmanName" readonly placeholder="请输入业务员名称">
            <template slot="append">
              <el-button type="primary" @click="openImportUser(1)">
                选择业务员
              </el-button>
            </template>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="协同人" prop="collaborator">
          <el-input v-model="form.collaborator" placeholder="请输入协同人" />
        </el-form-item>-->
        <el-form-item label="协同人名称" prop="collaboratorName">
          <el-input style="width: 250px" v-model="form.collaboratorName" readonly placeholder="请输入协同人名称">
            <template slot="append">
              <el-button type="primary" @click="openImportUser(2)">
                选择协同人
              </el-button>
            </template>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="信息提供人" prop="informationProvider">
          <el-input v-model="form.informationProvider" placeholder="请输入信息提供人" />
        </el-form-item>-->
        <el-form-item label="信息提供人名称" prop="informationProviderName">
          <el-input style="width: 250px" v-model="form.informationProviderName" readonly placeholder="信息提供人名称">
            <template slot="append">
              <el-button type="primary" @click="openImportUser(3)">
                选择提供人
              </el-button>
            </template>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="发起人所属部门" prop="sponsorDept">
          <el-input v-model="form.sponsorDept" placeholder="请输入发起人所属部门" />
        </el-form-item>-->

        <el-form-item label="项目名称" prop="projectName">
        <el-input style="width: 250px" v-model="form.projectName" placeholder="请输入项目名称" >
          <template slot="append">
            <el-button type="primary" @click="openProject">
              选择项目
            </el-button>
          </template>
        </el-input>
      </el-form-item>
        <el-form-item label="项目地区域" prop="projectArea">
          <el-select v-model="form.projectArea" placeholder="所属地区">
            <el-option
              v-for="item in regionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              @click.native="regionChange(item)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目信息来源" prop="projectSource">
          <el-select v-model="form.projectSource" placeholder="项目信息来源">
            <el-option
              v-for="item in projectSourceOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="收货人姓名" prop="consigneeName">
          <el-input v-model="form.consigneeName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="consigneeTel">
          <el-input v-model="form.consigneeTel" placeholder="请输入收货人电话" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address">
          <el-cascader v-model="form.addressOptions"
                       class="f-left"
                       :options="addressOptions"
                       @change="addressChange"
                       :props="optionProps"
                       placeholder="收货地址"
                       filterable
          ></el-cascader>
          <div style="margin-top: 10px"><el-input v-model="form.address" placeholder="请输入收货地址" /></div>

        </el-form-item>
        <el-form-item label="客户" prop="customerName">
          <el-input style="width: 250px" v-model="form.customerName" readonly placeholder="请选择客户">
            <template slot="append">
              <el-button type="primary" @click="openImportCustomer">
                选择客户
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="客户类别" prop="customerCategory">
          <el-select v-model="form.customerCategory" placeholder="客户类别">
            <el-option
              v-for="item in customerCategoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户信息来源" prop="customerSource">
          <el-select v-model="form.customerCategory" placeholder="客户信息来源">
            <el-option
              v-for="item in customerSourceOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户所属省份" prop="customerRegion">
          <el-input v-model="form.customerRegion"  readonly placeholder="请输入客户所属省份" />
        </el-form-item>
        <el-form-item label="订单发起日期" prop="orderDate">
          <el-date-picker clearable
            v-model="form.orderDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择订单发起日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务所属公司" prop="businessCompany">
          <el-select v-model="form.businessCompany" placeholder="业务所属公司">
            <el-option
              v-for="item in businessCompanyOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="form.orderType" placeholder="订单类型">
            <el-option
              v-for="item in orderTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="客户" prop="customerId">
          <el-input v-model="form.customerId" placeholder="请输入客户" />
        </el-form-item>-->


        <el-form-item label="租赁形式" prop="lease">
          <el-select v-model="form.lease" placeholder="租赁形式">
            <el-option
              v-for="item in leaseOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>


        <br/>

        <br/>
<!--        <el-form-item label="发货仓库id" prop="deliveryWarehouseId">
          <el-input v-model="form.deliveryWarehouseId" placeholder="请输入发货仓库id" />
        </el-form-item>-->
        <el-form-item label="发货仓库名称" prop="deliveryWarehouseName">
          <el-input style="width: 250px" v-model="form.deliveryWarehouseName" readonly placeholder="">
            <template slot="append">
              <el-button type="primary" style="width: 120px" @click="openImportWarehouse">
                选择仓库
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="产品关联" prop="productListStr">
          <div >
            <el-form  label-width="120px"  >

              <el-button type="primary" size="mini" @click="openProduct" style="margin-bottom: 10px">选择产品</el-button>
<!--              <div v-for="(item,index) in  models" :key="index" style="margin-top: 10px">-->
              <div style="margin-top: 10px">
                <el-form-item :prop="'model.1'"  label-width="0">
                  <div style="display:flex;">
                    <label class="whiteBankCard"
                           style="width: 130px;margin-right: 10px;text-align: center">整机品名</label>
                    <label class="whiteBankCard"
                              style="width: 130px;margin-right: 10px;text-align: center">型号</label>
                    <label class="whiteBankCard"
                              style="width: 130px;margin-right: 10px;text-align: center">数量</label>
<!--                    <label class="whiteBankCard"-->
<!--                           style="width: 130px;margin-right: 10px;text-align: center">未出库</label>-->
<!--                    <label class="whiteBankCard"-->
<!--                           style="width: 130px;margin-right: 10px;text-align: center">已出库</label>-->

                    <label class="whiteBankCard"
                           style="width: 130px;margin-right: 10px;text-align: center">日租金</label>

                    <label class="whiteBankCard"
                              style="width: 100px;margin-right: 10px;text-align: center">操作</label>

                  </div>
                 <div style="display:flex;" v-for="(item,index) in  productList"   :key="index">
                   <div :prop="'product.' + index">
                     <el-input class="whiteBankCard" readonly  v-model="item.productName"   placeholder="整机品名"
                               style="width: 130px;margin-right: 10px"></el-input>
                     <el-input class="whiteBankCard" readonly v-model="item.model" placeholder="型号"
                               style="width: 130px;margin-right: 10px"/>
                     <el-input class="whiteBankCard" v-model="item.quantity" @blur="NumberFn(index)" placeholder="数量"
                               style="width: 130px;margin-right: 10px"/>
<!--                     <el-input class="whiteBankCard" v-model="item.undeliveryQuantity" @blur="setDailyTotalRent(index)" placeholder="未出库"-->
<!--                               style="width: 130px;margin-right: 10px"/>-->
<!--                     <el-input class="whiteBankCard" v-model="item.deliveryQuantity" @blur="setDailyTotalRent(index)" placeholder="已出库"-->
<!--                               style="width: 130px;margin-right: 10px"/>-->
                     <el-input class="whiteBankCard" v-model="item.dailyRent" @blur="setDailyTotalRent(index,item.dailyRent)" placeholder="日租金（元／台／日）"
                               style="width: 130px;margin-right: 10px"/>



                     <el-button type="danger" size="mini"  style="height: 30px; margin-left:20px" @click="removeProduct(index)" >
                       删除
                     </el-button>
                   </div>
                  </div>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </el-form-item>
        <el-form-item label="辅料说明" prop="accessoriesInstruction">
          <el-input v-model="form.accessoriesInstruction" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="日租金合计" prop="totalDailyRent">
          <el-input v-model="form.totalDailyRent" placeholder="请输入日租金合计" />
        </el-form-item>
        <el-form-item label="租金合计" prop="totalRant">
          <el-input v-model="form.totalRant" placeholder="请输入租金合计" />
        </el-form-item>
        <el-form-item label="应收押金" prop="depositReceivable">
          <el-input v-model="form.depositReceivable" placeholder="请输入应收押金" />
        </el-form-item>
        <el-form-item label="押金收取方式" prop="depositCollectionMethod">
          <el-select v-model="form.depositCollectionMethod" placeholder="请选择付款方式">
            <el-option
              v-for="item in PaymentList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应收款" prop="receivables">
          <el-input v-model="form.receivables" placeholder="请输入应收款" />
        </el-form-item>
        <el-form-item label="已收款" prop="receivedAmount">
          <el-input @blur="receivedFn" v-model="form.receivedAmount" placeholder="请输入已收金额" />
        </el-form-item>

        <br>
        <el-form-item label="附件" prop="enclosure">
          <image-upload v-model="form.enclosure"/>

        </el-form-item>
        <el-form-item label="业务费情况" prop="businessExpenses">
          <el-input v-model="form.businessExpenses" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="期望到货日期" prop="expectedArrivalDate">
          <el-date-picker clearable
            v-model="form.expectedArrivalDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择期望到货日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="运输方式" prop="shippingType">-->
<!--          <el-select v-model="form.shippingType" placeholder="运输方式">-->
<!--            <el-option-->
<!--              v-for="item in shippingTypeOptions"-->
<!--              :key="item.dictValue"-->
<!--              :label="item.dictLabel"-->
<!--              :value="item.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="司机姓名" prop="driverName">-->
<!--          <el-input v-model="form.driverName" placeholder="请输入司机姓名" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="司机联系方式" prop="driverTel">-->
<!--          <el-input v-model="form.driverTel" placeholder="请输入司机联系方式" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="车辆信息" prop="vehicleInformation">-->
<!--          <el-input v-model="form.vehicleInformation" placeholder="请输入车辆信息" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="情况说明" prop="description">-->
<!--          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--      <el-form-item label="已收金额" prop="receivedAmount">-->
<!--          <el-input v-model="form.receivedAmount" placeholder="请输入已收金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="未收金额" prop="unreceivedAmount">-->
<!--          <el-input v-model="form.unreceivedAmount" placeholder="请输入未收金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="坏账金额" prop="badDebtAmount">-->
<!--          <el-input v-model="form.badDebtAmount" placeholder="请输入坏账金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="开票金额" prop="invoicedAmount">-->
<!--          <el-input v-model="form.invoicedAmount" placeholder="请输入开票金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="未开票金额" prop="uninvoicedAmount">-->
<!--          <el-input v-model="form.uninvoicedAmount" placeholder="请输入未开票金额" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="删除标志" prop="delFlag">-->
<!--          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />-->
<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <import-user ref="import" @showUser="showUser"></import-user>
    <import-customer ref="importCustomer" @showCustomer="showCustomer"></import-customer>
    <import-warehouse ref="importWarehouse" @showWarehouse="showWarehouse"></import-warehouse>
    <import-product ref="importProduct" @showProduct="showProduct"></import-product>
    <machine-list  ref="machineList"></machine-list>
     <project-list ref="project" @showProject="showProject"></project-list>
    <!--订单关联产品-->
    <el-dialog :title="productTitle" :visible.sync="productOpen" width="750px" >
      <div style="margin-top: 10px">
          <div style="display:flex;">
            <label class="whiteBankCard"
                   style="width: 100px;margin-right: 10px">整机品名</label>
            <label class="whiteBankCard"
                   style="width: 100px;margin-right: 10px">型号</label>
            <label class="whiteBankCard"
                   style="width: 100px;margin-right: 10px">数量</label>
            <label class="whiteBankCard"
                   style="width: 100px;margin-right: 10px">日租金</label>
            <label class="whiteBankCard"
                   style="width: 150px;margin-right: 10px">每日租金小计</label>
            <label class="whiteBankCard"
                   style="width: 120px;margin-right: 10px">出库数量</label>
            <label class="whiteBankCard"
                   style="width: 120px;margin-right: 10px">未出库数量</label>
            <label class="whiteBankCard"
                   style="width: 120px;margin-right: 10px">回货数量</label>
            <label class="whiteBankCard"
                   style="width: 100px;margin-right: 10px">备注</label>
          </div>
          <div style="display:flex; margin-top: 10px" v-for="(item,index) in  productList"   :key="index" >
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.productName }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.model }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.quantity }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.dailyRent }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.dailyTotalRent }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.deliveryQuantity }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.undeliveryQuantity }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.returnQuantity }}</label>
              <label class="whiteBankCard"
                     style="width: 100px;margin-right: 10px">{{ item.remark }}</label>
          </div>
      </div>
    </el-dialog>
    <el-dialog title="项目费用" :visible.sync="OneShow" width="40%"  >
      <el-button size="mini" type="success" @click="openHand">添加</el-button>
      <div style="margin-top: 10px; background-color: #f1f3f4">
        <el-table :data="moneyList">
          <el-table-column align="center" width="80" type="index" label="序号"></el-table-column>
          <el-table-column align="center" width="180" property="projectName" label="费用名称"></el-table-column>
          <el-table-column align="center" width="150" property="projectCost" label="金额"></el-table-column>
          <el-table-column align="center" width="100" label="操作">
            <template slot-scope="scope">
              <el-button type="text"  @click="editHand(scope.row)"> 修改</el-button>
              <el-button type="text"  @click="delHand(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="OneShow = false">取 消</el-button>

      </span>
    </el-dialog>
<!--    添加项目开发费用明细-->
    <!--    添加项目开发费用明细-->
    <el-dialog title="添加" :visible.sync="moneyShow" ref="moneyForm" width="30%" @close="closeFn">
      <el-form :model="moneyForm" label-width="100px">
        <!--      <el-form-item label="订单ID" prop="orderId"><el-input v-model="moneyForm.orderId"></el-input></el-form-item>-->
        <el-form-item label="费用名称" prop="projectName"><el-input v-model="moneyForm.projectName"  placeholder="请填写费用名称"></el-input></el-form-item>
        <el-form-item label="金额" prop="projectCost"><el-input v-model="moneyForm.projectCost" placeholder="请填写金额"></el-input></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="moneyShow=false">取 消</el-button>
        <el-button type="primary" @click="handOk">确 定</el-button>
      </span>
    </el-dialog>
<!--    追加押金-->
    <el-dialog title="追加押金" :visible.sync="addmoneyShow" width="30%" @close="addMoneyClose">
      <el-form :model="addmoneyForm" label-width="100px">
        <el-form-item prop="adddepositReceivable" label="追加金额"><el-input v-model="addmoneyForm.adddepositReceivable" placeholder="请输入追加金额（/元）"></el-input></el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addmoneyShow=false">取 消</el-button>
        <el-button type="primary" @click="addMoneyBtn">确 定</el-button>
      </span>
    </el-dialog>
<!--    审批记录-->
    <el-dialog title="审批记录" :visible.sync="approvalShow"  width="1000px">
      <el-table :data="ApprovalList">
        <el-table-column align="center" width="80" type="index" label="序号"></el-table-column>
        <el-table-column align="center" width="180" property="orderNo" label="订单编号"></el-table-column>
        <el-table-column align="center" width="150" property="marketingUserName" label="市场部审批人"></el-table-column>
        <el-table-column align="center" width="150" property="createTime" label="审批时间"></el-table-column>
        <el-table-column align="center" width="180" property="financeUserName" label="财务部审批人"></el-table-column>
        <el-table-column align="center" width="150" property="updateTime" label="审批时间"></el-table-column>

      </el-table>

    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder,getWaringOrderList ,updateOrderStatus,updateOrderStatus1,updateOrderStatus2} from "@/api/module/order";
import {getLoginUser} from "@/api/system/user"
import { provinceNameList } from '@/api/module/region';
import { getDicts } from '@/api/system/dict/data';
import importUser from "../customer/user";
import importCustomer from "@/views/module/follow/customer";
import importWarehouse from "@/views/module/product/warehouse";
import importProduct from "@/views/dialog/product";
import machineList from "@/views/module/order/machineoederlist";
import ProjectList from '@/views/module/order/project'
import { getMachineList,getMachineList2 } from '@/api/module/order.js';
import {addProjectExpendApi, delProjectExpendApi, editProjectExpendApi, getProjectExpendApiInfoApi, getProjectExpendListApi} from "@/api/module/reported";
import Project from "@/views/module/project";
import { listStock, getStock, delStock, addStock, updateStock ,listStock2} from "@/api/module/stock";
import {getApprovalInfo,getApprovalList,editApprovalInfo,addApproval} from '@/api/module/approval'
export default {
  name: "Order",
  components: {Project, importUser ,importCustomer,importWarehouse,importProduct,machineList,ProjectList},

  data() {
    var validatePhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入电话号码'))
      }
      if (value.length !== 11) {
        callback(new Error('请输入正确电话号码'))
      }
      if (value.length !== 11) {
        callback(new Error('请输入正确电话号码'))
      }
      // 验证电话号码手机号码，包含至今所有号段? ?
      var ab = /^[1][3|4|5|6|7|8|9][0-9]{9}$/
      if (ab.test(value) === false) {
        callback(new Error('请输入正确电话号码'))
      }
      callback()
    }


    return {
      //审批记录
      ApprovalList:[],//审批记录
      approvalShow:false,//审批展示
      newArr:[],
      // 弹出层标题
      productTitle: "",
      // 是否显示弹出层
      productOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractTemplate: null,
        sponsor: null,
        sponsorName: null,
        salesman: null,
        salesmanName: null,
        collaborator: null,
        collaboratorName: null,
        informationProvider: null,
        informationProviderName: null,
        sponsorDept: null,
        sponsorDeptName: null,
        orderNo: null,
        orderDate: null,
        businessCompany: null,
        orderType: null,
        customerId: '',
        customerName: null,
        customerCategory: null,
        customerSource: null,
        customerRegion: null,
        projectName: null,
        projectArea: null,
        projectSource: null,
        projectId:'',
        lease: null,
        address: null,
        consigneeName: null,
        consigneeTel: null,
        deliveryWarehouseId: null,
        deliveryWarehouseName: null,
        accessoriesInstruction: null,
        totalDailyRent: null,
        totalRant: null,
        depositReceivable: null,
        depositCollectionMethod: null,
        receivables: null,
        enclosure: null,
        businessExpenses: null,
        expectedArrivalDate: null,
        shippingType: null,
        driverName: null,
        driverTel: null,
        vehicleInformation: null,
        shipmentStatus: null,
        orderStatus: null,
        description: null,
        deliveryStatus: null,
        receivedAmount: null,
        unreceivedAmount: null,
        badDebtAmount: null,
        invoicedAmount: null,
        uninvoicedAmount: null,
      },
      // 表单参数
      form: {
      productList:[],
        purview:'2'

      },
      //项目支出明细弹框
      OneShow:false,
      moneyList:[],
      //费用添加弹框是否打开
      moneyShow:false,
      moneyForm:{
        orderId:null,
        projectName:null,
        projectCost:null,
      },
      // 表单校验
      rules: {
        contractTemplate:[{required:true,message:'请选择合同类型',trigger:'blur'}],
        salesmanName:[{required:true,message:'请选择业务人员',trigger:'blur'}],
        orderDate:[{required:true,message:'请选择业订单创建日期',trigger:'blur'}],
        businessCompany:[{required:true,message:'请选择业务所属公司',trigger:'blur'}],
        orderType:[{required:true,message:'请选择订单类型',trigger:'blur'}],
        customerName:[{required:true,message:'请输入客户信息',trigger:'blur'}],
        projectName:[{required:true,message:'请输入项目名称',trigger:'blur'}],
        projectArea:[{required:true,message:'请输入项目地址',trigger:'blur'}],
        projectSource:[{required:true,message:'请输入项目来源',trigger:'blur'}],
        lease:[{required:true,message:'请选择租赁形式',trigger:'blur'}],
        address:[{required:true,message:'请选择收货地址',trigger:'blur'}],
        deliveryWarehouseName:[{required:true,message:'请选择仓库',trigger:'blur'}],
        consigneeName:[{required:true,message:'请输入收货人姓名',trigger:'blur'}],
        consigneeTel:[{required:true,message:'请输入收货人电话',trigger:'blur'},{ validator: validatePhone, trigger: 'blur' }],
        shippingType:[{required:true,message:'请输选择运输方式',trigger:'blur'}],
        receivedAmount:[{required:true,message:'请输入以收金额',trigger:'blur'}],
        // driverName:[{required:true,message:'请输入司机姓名',trigger:'blur'}],
        // driverTel:[{required:true,message:'请输入司机电话',trigger:'blur'},{ validator: validatePhone, trigger: 'blur' }],
        // vehicleInformation:[{required:true,message:'请输入车辆信息',trigger:'blur'}],
      },
      regionOptions: [], //地区选择列表
      addressOptions: [], //地址选择列表
      contractTemplateOptions: [], // 合同模板
      businessCompanyOptions: [], // 业务所属公司
      orderTypeOptions: [], // 订单类型
      projectSourceOptions: [], // 项目信息来源
      leaseOptions: [], // 租赁形式
      shippingTypeOptions: [], // 运输方式
      customerCategoryOptions:[],//客户类别
      customerSourceOptions:[],//客户来源
      customerRegionOptions:[],
      PaymentList:[],
      optionProps: {
        value: 'label',
        label: 'label',
        children: 'children'
      },
      // 是否显示用户弹出层
      openUser: false,
      user:{},
      productList: [],
      addmoneyShow:false,//追加押金
      addmoneyForm:{
        adddepositReceivable:'',//追加金额
      },


    };
  },

  created() {

    this.getAreaList();
    this.getContractTemplateOptions();
    this.getBusinessCompanyOptions();
    this.getOrderTypeOptions();
    this.getProjectSourceOptions();
    this.getLeaseOptions();
    this.getShippingTypeOptions();
    this.getsponsor();
     this.getPayment()
   this.getcustomerCategoryOptions()
    this.getcustomerSourceOptions()
    this.getList();
  },

  methods: {
    //市场部审批
   async  updateFn1(val){
      //权限内审批，周总审批
     if(val.purview=='2'){
       await this.$confirm('请确认是否通过审批')

       //增加审批记录
       await addApproval({orderId: val.id,orderNo:val.orderNo,marketingUserId:this.user.userId,marketingUserName:this.user.username,})
       //0-8
       await updateOrderStatus1({id: val.id})
       await this.getList()
     }else{

       //增加审批记录
       await addApproval({orderId: val.id,orderNo:val.orderNo,marketingUserId:this.user.userId,marketingUserName:this.user.username,})
       //  0-11
       await updateOrderStatus2({id:val.id})
     }

         },
    //市场部超权限审批
    async updateFn2(val){
      await updateOrderStatus1({id:val.id})
      //增加财务审批记录（修改操作）
      let res=await getApprovalList({orderId:val.id})
      console.log(res)
      await editApprovalInfo({id:res.rows[0].id,marketedUserId: this.user.userId,marketedUserName: this.user.username})

    },
    //财务部审批
    async  updateFn(val){
      await this.$confirm('请确认是否通过审批')
      await updateOrderStatus({id:val.id})
      //增加财务审批记录（修改操作）
       let res=await getApprovalList({orderId:val.id})
      console.log(res)
      await editApprovalInfo({id:res.rows[0].id,orderId: res.rows[0].orderId,orderNo:res.rows[0].orderNo,marketingUserId:res.rows[0].marketingUserId,marketingUserName: res.rows[0].marketingUserName,financeUserId:this.user.userId,financeUserName:this.user.username})
      await this.getList()
    },
    //打开审批记录弹框
   async  openApproval(val){
     this.approvalShow=true
    //  获取记录
        let res=await getApprovalList({orderNo:val.orderNo})
     this.ApprovalList=res.rows
    },
    /** 打开产品弹窗 */
    openProduct() {
      this.$refs.importProduct.show();
      console.log( this.$refs.importProduct.show())
    },
    showProduct(data){
      this.productList.push(...data);
      console.log(this.productList)
    },
    removeProduct(index) {
      this.productList.splice(index, 1)
    },
    //获取库存数量

    //数量校验库存
    async NumberFn(index){
      console.log(index)
      console.log(this.productList[index].model)
        let res=await listStock2({warehouseName:this.form.deliveryWarehouseName})
      res.rows.forEach(item=>{
        if(item.model===this.productList[index].model){
                    if(item.availableQuantity <this.productList[index].quantity){
                      this.$message.warning(`当前仓库${item.model}可用库存数量为${item.availableQuantity}`)
                      this.productList[index].quantity=null
                    }
        }
      })
    },

    setDailyTotalRent(index,val){
      // console.log(index)
     /* var total = 0;
      if( this.productList[index].quantity && this.productList[index].dailyRent){
        total = parseFloat(this.productList[index].quantity) * parseFloat( this.productList[index].dailyRent);
      }
      this.productList[index].dailyTotalRent = total;*/
      // this.productList.forEach((item,index)=>{
      //
      // })

      //计算日租金
      let total=0
      let totalCash=0
      let arr=[]
      let arr1=[]
      this.productList.forEach((item,index)=>{
        if( item.quantity && item.dailyRent){
            total = parseFloat(item.quantity) * parseFloat( item.dailyRent);
          totalCash=parseFloat(item.price)*parseFloat(item.quantity)
          arr1.push(totalCash)
            arr.push(total)
          }
        // console.log(arr)
       let sum= arr.reduce(function(prev, cur, index) {
          return prev + cur;
        })
        let sum1=arr1.reduce(function(prev, cur, index) {
          return prev + cur;
        })
        this.form.depositReceivable=sum1
        // console.log(sum)
        this.form.totalDailyRent=sum

      })
    //  判断日租金是否符合标准
           if(parseFloat(val)<150){
             this.form.purview='1'
           }

    },
    receivedFn(){
      if(parseFloat(this.form.receivedAmount)<parseFloat(this.form.depositReceivable)){
        this.form.purview='1'
      }
    },
    /** 打开仓库弹窗 */
    openImportWarehouse() {
      this.$refs.importWarehouse.show(1);
    },
    showWarehouse(data){
      //仓库
      this.form.deliveryWarehouseId=data.id;
      this.form.deliveryWarehouseName=data.name;
    },
    /** 打开客户弹窗 */
    openImportCustomer() {
      this.$refs.importCustomer.show();
    },
    showCustomer(data){
      this.form.customerId=data.customerId;
      this.form.customerName=data.customerName;
      this.form.customerCategory=data.category;
      this.form.customerSource=data.source;
      this.form.customerRegion=data.region;

    },
    //打开项目弹框
    openProject(){
          this.$refs.project.isShow=true
    },
    showProject(data){
      console.log(data)
      // this.form.customerName=data.customerName
      // this.form.customerId=data.customerId
      this.form.consigneeName=data.receiverName
      this.form.consigneeTel=data.projectTel
      this.form.address=data.projectAddress
      this.form.projectName=data.projectName
      this.form.projectId=data.id
      this.form.projectArea=data.projectArea
      this.form.projectAreaName=data.projectAreaName
      this.form.projectSource=data.projectSource


    },
    //获取发起人
    getsponsor(){
      getLoginUser(this.queryParams).then(response => {
        this.user = response.user;
      })
    },

    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        // 产品类型判断
        let arr = this.orderList;
        arr.forEach(item => {
          item.contractTemplate = this.getValue(this.contractTemplateOptions, item.contractTemplate)
          item.businessCompany = this.getValue(this.businessCompanyOptions, item.businessCompany)
          item.orderType = this.getValue(this.orderTypeOptions, item.orderType)
          item.projectSource = this.getValue(this.projectSourceOptions, item.projectSource)
          item.lease = this.getValue(this.leaseOptions, item.lease)
          item.shippingType = this.getValue(this.shippingTypeOptions, item.shippingType)
          item.customerSource=this.getValue(this.customerSourceOptions,item.customerSource)
          item.customerCategory=this.getValue(this.customerCategoryOptions,item.customerCategory)
          item.depositCollectionMethod=this.getValue(this.PaymentList,item.depositCollectionMethod)
        });
        this.orderList = arr;
        this.total = response.total;
        this.loading = false;
      });
    },
    getValue(arr, item) {
      for (let i = 0; i < arr.length; i++) {
        if (item === arr[i].dictValue) {
          return arr[i].dictLabel
        }
      }
    },
    //获取客户类别
    async getcustomerCategoryOptions(){
        let res= await getDicts('biz_category')
      this.customerCategoryOptions=res.data
    },
    //获取客户来源
    async getcustomerSourceOptions(){
    let res=await getDicts('biz_source')
        this.customerSourceOptions=res.data
    },
    //

    //获取地区选择
    getAreaList() {
      provinceNameList().then(res => {
        this.regionOptions = res.rows;
        let arr = JSON.parse(JSON.stringify(res.rows)) //深拷贝
        /*    arr.forEach(item => {
              item.children.forEach(cItem => delete cItem.children)
            })
            debugger*/
        this.addressOptions = arr
      })
    },
    // 地址选择
    addressChange(value) {
      console.log(value)
      if(value && value.length>0){
        this.form.address = value[0]+value[1]+value[2];
      }

    },
    // 地址选择
    regionChange(value) {
      this.form.projectAreaName=value.label;
      this.form.projectArea=value.value;
    },
    /** 打开用户弹窗 */
    openImportUser(num) {
      this.$refs.import.show(num);
    },

    showUser(data){
      if(data.type == 1){
        //业务员
        this.form.salesman=data.userId;
        this.form.salesmanName=data.userName;
      }else if(data.type==2){
        //协同人
        this.form.collaborator=data.userId;
        this.form.collaboratorName=data.userName;
      }else if(data.type==3){
        //信息提供人
        this.form.informationProvider=data.userId;
        this.form.informationProviderName=data.userName;
      }
    },

    // 获取合同模板
    getContractTemplateOptions() {
      getDicts('biz_contract_template').then(response => {
        this.contractTemplateOptions = response.data
      })
    },
    // 获取 业务所属公司
    getBusinessCompanyOptions() {
      getDicts('biz_business_company').then(response => {
        this.businessCompanyOptions = response.data
      })
    },
    // 获取订单类型
    getOrderTypeOptions() {
      getDicts('biz_order_type').then(response => {
        this.orderTypeOptions = response.data
      })
    },
    // 获取项目信息来源
    getProjectSourceOptions() {
      getDicts('biz_project_source').then(response => {
        this.projectSourceOptions = response.data
      })
    },
    // 获取租赁形式
    getLeaseOptions() {
      getDicts('biz_lease').then(response => {
        this.leaseOptions = response.data
      })
    },// 获取运输方式
    getShippingTypeOptions() {
      getDicts('biz_shipping_type').then(response => {
        this.shippingTypeOptions = response.data
      })
    },

    //获取支付方式
    getPayment(){
      getDicts('pay_ment').then(response=>{
        this.PaymentList=response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractTemplate: null,
        sponsor: null,
        sponsorName: null,
        salesman: null,
        salesmanName: null,
        collaborator: null,
        collaboratorName: null,
        informationProvider: null,
        informationProviderName: null,
        sponsorDept: null,
        sponsorDeptName: null,
        orderNo: null,
        orderDate: null,
        businessCompany: null,
        orderType: null,
        customerId: null,
        customerName: null,
        customerCategory: null,
        customerSource: null,
        customerRegion: null,
        projectName: null,
        projectArea: null,
        projectSource: null,
        lease: null,
        address: null,
        consigneeName: null,
        consigneeTel: null,
        deliveryWarehouseId: null,
        deliveryWarehouseName: null,
        accessoriesInstruction: null,
        totalDailyRent: null,
        totalRant: null,
        depositReceivable: null,
        depositCollectionMethod: null,
        receivables: null,
        enclosure: null,
        businessExpenses: null,
        expectedArrivalDate: null,
        shippingType: null,
        driverName: null,
        driverTel: null,
        vehicleInformation: null,
        shipmentStatus: null,
        orderStatus: null,
        description: null,
        deliveryStatus: null,
        receivedAmount: null,
        unreceivedAmount: null,
        badDebtAmount: null,
        invoicedAmount: null,
        uninvoicedAmount: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        createTime: null,
        delFlag: null
      };
      this.resetForm("form");
      this.productList=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log(selection)
      this.ids = selection.map(item => item.id)
      console.log(this.ids)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //项目开发费用明细
    // 弹框打开
   async openProjectList(val){
    this.OneShow=true
    //根据项目，项目名称选择
     console.log(val)
      this.moneyForm.projectName=val.projectName
        let res=await getProjectExpendListApi({projectName:this.moneyForm.projectName})
     this.moneyList=res.rows
    },
// /项目开发费用明细
// 弹框打开
   openHand(){
  this.moneyShow=true


    },
    async editHand(val){
     this.moneyShow=true
     let res=await getProjectExpendApiInfoApi(val.id)
     this.moneyForm=res.data
    },
    async handOk(){
   try{
    // await this.$refs.moneyForm.validate()
    if(this.moneyForm.id){
      await editProjectExpendApi(this.moneyForm)
    }else{
      await addProjectExpendApi(this.moneyForm)
    }
    this.$message.success('操作成功')
    this.moneyShow=false
     console.log(this.moneyForm)
     let res=await getProjectExpendListApi(this.moneyForm)
     this.moneyList=res.rows
  }catch (error){
    console.log(error)
  }

},
//删除
 async delHand(val){
  await this.$confirm('是否删除')
  await  delProjectExpendApi(val.id)
  this.$message.success('删除成功')
   console.log(val)
  let res=await getProjectExpendListApi({projectName:val.projectName})
  this.moneyList=res.rows
},
//弹框关闭
async closeFn(){
  // this.moneyForm={
  //   orderId:null,
  //   projectName:null,
  //   projectCost:null
  // }
  this.moneyForm.orderId=null
  this.moneyForm.projectCost=null

},

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
      this.form.sponsor=this.user.userId;
      this.form.sponsorName=this.user.username;
      this.form.salesman=this.user.userId;
      this.form.salesmanName=this.user.username;
      this.form.sponsorDept=this.user.user.dept.deptId;
      this.form.sponsorDeptName=this.user.user.dept.deptName;
      this.form.orderNo=this.setOrderNo();
    },
    setOrderNo(){
      var date = new Date();
      var year = date.getFullYear();        //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1;      //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate();             //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
      //修改月份格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      //修改日期格式
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }

      let round = Math.floor(Math.random() * (999 - 100)) + 100;
      var currentFormatDate = `${year}${month}${day}`;
      return "ZLDD"+currentFormatDate+round;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.productList=row.productList;
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        this.form.productList=this.productList;

        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查看关联产品 */
    handleProduct(row) {
      this.productList=row.productList;
      this.productOpen = true;
      this.productTitle = "关联产品";
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    /** 控制维修订单按钮 */
   async handelerOrderList(val){
      console.log(val)
      this.$refs['machineList'].isShow=true
      const res= await getMachineList2({
        orderId:val.id
      })
      console.log(res)
      this.$refs.machineList.tableData=res.rows

      this.$refs.machineList.addFormData.orderId=val.id
      this.$refs.machineList.addFormData.orderNo=val.orderNo
      this.$refs.machineList.id=val.id
    },
    //查看预警订单
   async handleWaring(){
     let data={}
          let res=await getWaringOrderList()
     console.log(res)
     this.orderList=res.rows
     await this.$message.success('当前为预警订单')
    },
    async addmoney(val){
    // 弹框打开
      this.addmoneyShow=true
    //  获取当前数据
      let res= await getOrder(val)
      this.form=res.data

    },
    async addMoneyBtn(){
      //  修改金额
      this.form.depositReceivable=Number(this.form.depositReceivable)+Number(this.addmoneyForm.adddepositReceivable)

      await this.$confirm(`是否确认追加${this.addmoneyForm.adddepositReceivable}元押金`)
     await updateOrder(this.form)
      this.$message.success('追加押金成功')
      this.addmoneyShow=false
    },
    async addMoneyClose(){
     this.addmoneyForm={
        adddepositReceivable:'',//追加金额
      }
      this.form={}
      await this.getList()
    }

  }
};
</script>
